package com.dxyxx.framework;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import br.com.pierry.simpletoast.SimpleToast;

import com.dxyxx.R;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.Group;
import com.dxyxx.pojo.Order;
import com.dxyxx.pojo.OrderDetail;
import com.dxyxx.pojo.ResponseResult;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class OrderUndoneActivity extends BasePayActivity {
	private ViewGroup rootViewGroup;
	private DecimalFormat df = new DecimalFormat("######0.00");
	private Order order;
	private ProgressDialog progressDialog;
	private char c;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_orderundone);
		initViews();
		rootViewGroup = (ViewGroup) findViewById(R.id.content);
		// 根据id 拿到信息。
		RequestParams rp = new RequestParams();
		Bundle bundle = this.getIntent().getExtras();
		rp.add("id", bundle.getString("id"));
		String url = null;

		c = bundle.getString("uuid").charAt(0);
		switch (c) {
		case 'g':// 开团吧
			url = "gorder/findById";
			break;
		case 'o':
			url = "order/findById";
			break;
		case 't':
			url = "order/findTicketById";
			break;
		default:
			url = "order/findById";
			break;
		}
		// 启动 等待框架
		progressDialog = ProgressDialog.show(this, null, null);
		progressDialog.setContentView(R.layout.dialog_circle);
		HttpUtil.get(url, rp, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				AgainPlayer.makeCall(OrderUndoneActivity.this, "网络好像出错了");
				progressDialog.dismiss();
			}

			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				progressDialog.dismiss();
				try {
					JavaType type = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, Order.class);

					ResponseResult<Order> result = getObjectMapper().readValue(new String(arg2), type);
					if (result.getCode() == 1) {
						order = result.getObject();
						orderMoney.setText("￥" + df.format(order.getMoney()));

						orderDeliveryType.setText("自提");
						switch (order.getBufferInterval()) {
						case 0:
							et_dtime.setText("当天");
							break;
						case 1:
							et_dtime.setText("下单后第二天");
							break;
						case 2:
							et_dtime.setText("下单后第三天");
							break;

						default:
							et_dtime.setText("当天");
							break;
						}

						//					orderId.setText(order.getUuid());

						if (order.getPayType().equals("alipay")) {
							et_payType.setImageResource(R.drawable.alipay_icon);
						} else {
							et_payType.setImageResource(R.drawable.wechat);
						}
						//Order 
						if (order.getOrderDetails() != null) {
							for (OrderDetail od : order.getOrderDetails()) {
								View view = (ViewGroup) getLayoutInflater().inflate(R.layout.item_orderconfirm, null, false);
								((TextView) view.findViewById(R.id.price)).setText(od.getPrice() + "");
								((TextView) view.findViewById(R.id.amount)).setText("*" + od.getAmount() + "=  ");
								((TextView) view.findViewById(R.id.all)).setText(df.format(od.getPrice() * od.getAmount()));
								((TextView) view.findViewById(R.id.description)).setText(od.getProduct().getDescription());
								((TextView) view.findViewById(R.id.specification)).setText(od.getProduct().getSpecification());
								imageLoader.displayImage(baseImageURL + od.getProduct().getThumbId() + "?p=0", (ImageView) view.findViewById(R.id.thumb), squareOptions, animateFirstListener);
								rootViewGroup.addView(view);
							}
						}
						// GroupOrder
						Group group = order.getGroup();
						if (group != null) {//属于团购
							View view = (ViewGroup) getLayoutInflater().inflate(R.layout.item_orderconfirm, null, false);
							((TextView) view.findViewById(R.id.price)).setText(group.getPersonPrice() + "");
							((TextView) view.findViewById(R.id.amount)).setText("*1" + "=  ");
							((TextView) view.findViewById(R.id.all)).setText(group.getPersonPrice() + "");
							((TextView) view.findViewById(R.id.description)).setText(group.getProduct().getDescription());
							((TextView) view.findViewById(R.id.specification)).setText(group.getProduct().getSpecification());
							imageLoader.displayImage(baseImageURL + group.getProduct().getThumbId() + "?p=0", (ImageView) view.findViewById(R.id.thumb), squareOptions, animateFirstListener);
							rootViewGroup.addView(view);
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		});

	}

	private TextView orderMoney;
	private TextView orderDeliveryType;
	private TextView et_dtime;// 自提时间
	//	private TextView orderId;
	private ImageView et_payType;
	private Context context;

	public void initViews() {
		context = this;
		((ImageView) findViewById(R.id.backImageButton)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		((ImageView) findViewById(R.id.nextImageButton)).setVisibility(View.INVISIBLE);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("待付款");
		title.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
		///

		orderMoney = (TextView) findViewById(R.id.orderMoney);
		orderDeliveryType = (TextView) findViewById(R.id.orderDeliveryType);
		et_dtime = (TextView) findViewById(R.id.et_dtime);
		//		orderId = (TextView) findViewById(R.id.orderId);
		et_payType = (ImageView) findViewById(R.id.payIcon);

		Button payButton = (Button) findViewById(R.id.payButton2);
		payButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				//判断是否超时了？24小时
				if (!jisuan(order.getPostTime(), new Date())) {
					SimpleToast.error(OrderUndoneActivity.this, "订单已经超过24小时，无效了");
					return;
				}

				if (order.getPayType().equals("tenpay")) {
					userPreferences = UserPreferences.getInstance(getApplicationContext());
					userPreferences.setPayType("o");
					tenPay(OrderUndoneActivity.this, progressDialog, order.getUuid());
					//					finish();//关掉页面
				} else {
					alipay(order.getUuid(),order.getMoney());
					SimpleToast.info(getApplicationContext(), "支付宝");
				}

			}
		});
		// 检查是否 超时。TODO TODO
		Button cancelButton = (Button) findViewById(R.id.cancelButton2);
		cancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String urlString = "order/cancelOrder";
				switch (c) {
				case 'g':// 开团吧
					urlString = "gorder/cancelOrder";
					break;
				case 'o':
					urlString = "order/cancelOrder";
					break;

				default:
					urlString = "order/cancelOrder";
					break;
				}

				RequestParams ps = new RequestParams();
				ps.add("orderId", order.getId() + "");

				progressDialog.show();
				HttpUtil.post(urlString, ps, new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						progressDialog.dismiss();

						AgainPlayer.makeCall(OrderUndoneActivity.this, "网络好像出错了");
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						progressDialog.dismiss();
						try {
							JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, Object.class);
							ResponseResult<Object> rr = getObjectMapper().readValue(arg2, javaType);
							if (rr.getCode() == 1) {
								SimpleToast.info(OrderUndoneActivity.this, "取消成功");
								Intent intent2 = new Intent();

								intent2.setClass(OrderUndoneActivity.this, OrderListActivity.class);
								// 关闭Activity
								intent2.putExtra("result", true);
								// 设置返回数据
								OrderUndoneActivity.this.setResult(1, intent2);
								OrderUndoneActivity.this.finish();
							} else {
								SimpleToast.info(OrderUndoneActivity.this, rr.getInfo());
							}
						} catch (JsonParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JsonMappingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});

			}
		});
	}

}
